<template>
  <div>
    <div>
      <el-radio name="ab" v-model="value" :label="true">图片</el-radio>
      <el-radio name="ab" v-model="value" :label="false">文本</el-radio>
    </div>
    <el-container>
      <el-input placeholder="请输入内容" v-model="text1" class="input-with-select" :disabled="value"></el-input>
    </el-container>
    <el-container>
      <el-upload action="#" :http-request="request" :disabled="!value" :show-file-list="false" :limit="1" ref="upload">
        <template #default>
          <el-button v-if="!image" :disabled="!value">
            <el-icon>
              <CirclePlus />
            </el-icon>
          </el-button>
          <el-image v-else :src="image" class="el-images"></el-image>
        </template>
      </el-upload>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { CirclePlus } from '@element-plus/icons-vue';
import { ElUpload } from "element-plus";
import { computed, ref, watch } from "vue";
import updateoss from "../../util/updateoss";
const p = defineProps<{ change?: (text: string, image: string) => void, text: string }>()
const dialogVisible = ref(false);
const disabled = ref(false);

const upload = ref<typeof ElUpload>();

const pt = computed<{ type: "image" | "text" }>(() => {
  const R = new RegExp(/\.(png|jpg|gif|jpeg|webp)$/);
  const t = R.test(p.text);
  if (t) {
    return {
      type: "image",
    };
  } else {
    return {
      type: "text",
    };
  }
});
const value = ref(pt.value.type === "text" ? false : true);
async function request(file: any, cb: any) {
  const data = await updateoss([file.file], cb);
  if (data) {
    image.value = data.url;
    upload.value?.clearFiles();
  }
}
const image = ref(pt.value.type === "image" ? p.text : "");
const text1 = ref(pt.value.type === "text" ? p.text : "");
watch(
  () => p.text,
  () => {
    text1.value = p.text;
  }
);

watch(text1, () => {
  if (p.change) p.change(text1.value, "");
  upload.value?.clearFiles();
});

watch(image, () => {
  if (p.change) p.change("", image.value);
  upload.value?.clearFiles();
});
</script>

<style scoped>
.avatar {
  width: 160px;
  height: 90px;
}

.disabled {
  cursor: not-allowed;
}

.el-images {
  width: 160px;
}
</style>
